package com.common.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.common.core.base.model.LoginUser;

import com.common.core.utils.JwtUtil;
import com.common.security.db.cache.TokenCache;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class TokenService {

    @Resource
    private TokenCache tokenCache;

    @Resource
    private HttpServletRequest request;

    public LoginUser getUser(String token) {
        String userId = JwtUtil.getUsernameFromToken(token);
        return tokenCache.getToken(Long.valueOf(userId));
    }

    public Boolean verifyToken(String token) {
        if (!JwtUtil.validateToken(token)) {
            return false;
        }
        LoginUser loginUser = getUser(token);
        if (ObjectUtil.isEmpty(loginUser)) {
            return false;
        }
        tokenCache.setToken(loginUser.getUserId(),loginUser);
        return true;
    }

    public void setAuthentication(String token) {
        LoginUser loginUser = this.getUser(token);
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        // 设置认证的细节信息，如请求的URL等
        // 使用 RequestContextHolder 获取当前请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetailsSource().buildDetails(request);
            authentication.setDetails(webAuthenticationDetails);
        }
        // 设置当前的认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
